package org.example.weboj.controller;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Optional;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import org.example.weboj.entity.User;
import org.example.weboj.service.IUserService;
import org.example.weboj.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import lombok.Data;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private IUserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
        try {
            // 使用 Spring Security 的 AuthenticationManager 进行身份验证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
            );

            // 认证成功后，加载用户信息
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();

            Optional<User> optionalUser = userService.findByUsername(userDetails.getUsername());
            // 使用 JwtUtils 生成 Token
            if (optionalUser.isPresent()) {
                String token = jwtUtils.generateToken(optionalUser.get());
                return ResponseEntity.ok().body(Map.of(
                        "username", optionalUser.get().getUsername(),
                        "token",token,
                        "role", optionalUser.get().getRole()));
            } else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(Map.of("error", "用户信息异常，请联系管理员"));
            }
        } catch (BadCredentialsException e) {
            // 捕获认证失败的异常，返回自定义错误信息
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Map.of("error", "用户名或密码错误"));
        } catch (AuthenticationException e) {
            // 捕获其他认证相关的异常，返回通用的错误信息
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Map.of("error", "认证失败，请稍后再试"));
        }
    }

//    @PostMapping("/login")
//    public ResponseEntity<?> login(@RequestBody LoginRequest request) {
//        Optional<User> userOpt = userService.authenticate(request.getUsername(), request.getPassword());
//
//        if (userOpt.isPresent()) {
//            User user = userOpt.get();
//            return ResponseEntity.ok(Map.of(
//                    "username", user.getUsername(),
//                    "token", "mock-jwt-token", // In a real application, you would generate a JWT token here
//                    "role", user.getRole()
//            ));
//        } else {
//            return ResponseEntity.status(401).body(Map.of("error", "用户名或密码错误"));
//        }
//    }


    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody RegisterRequest request) {
        String username = request.getUsername();
        String email = request.getEmail();
        String password = request.getPassword();

        // 1. 检查用户名是否已存在
        if (userService.findByUsername(username).isPresent()) {
            return ResponseEntity.badRequest().body(Map.of("error", "用户名已存在"));
        }

        // 2. 创建用户对象并设置基本信息
        User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        user.setRole("USER");
        user.setCreatedAt(LocalDateTime.now());

        // 3. 使用 Spring Security 的 PasswordEncoder 进行密码加密
        String hashedPassword = passwordEncoder.encode(password);
        user.setPasswordHash(hashedPassword);

        // 4. 保存用户
        userService.save(user);

        // 5. 返回成功响应（不含密码）
        return ResponseEntity.ok(Map.of(
                "message", "注册成功",
                "username", user.getUsername(),
                "email", user.getEmail()
        ));
    }



//    @PostMapping("/register")
//    public ResponseEntity<?> registerUser(@RequestBody RegisterRequest request) {
//        String username = request.getUsername();
//        String email = request.getEmail();
//        String password = request.getPassword();
//        // Check if username already exists
//        if (userService.findByUsername(username).isPresent()) {
//            return ResponseEntity.badRequest().body("Username already exists");
//        }
//
//        // Create new user
//        User user = new User();
//        user.setUsername(username);
//        user.setEmail(email);
//        // Hash password using MD5
//        try {
//            MessageDigest digest = MessageDigest.getInstance("MD5");
//            byte[] hash = digest.digest(password.getBytes());
//            StringBuilder hexString = new StringBuilder();
//            for (byte b : hash) {
//                String hex = Integer.toHexString(0xff & b);
//                if (hex.length() == 1) hexString.append('0');
//                hexString.append(hex);
//            }
//            user.setPasswordHash(hexString.toString());
//        } catch (NoSuchAlgorithmException e) {
//            return ResponseEntity.internalServerError().body("Error processing password");
//        }
//
//        // Set default values
//        user.setRole("USER");
//        user.setCreatedAt(LocalDateTime.now());
//
//        // Save user
//        userService.save(user);
//
//        // Return user without password hash
//        user.setPasswordHash(null);
//        return ResponseEntity.ok(user);
//    }
}

// 登录请求对象
@Data
class LoginRequest {
    private String username;
    private String password;
}
@Data
class RegisterRequest {
    @NotBlank
    private String username;
    @Email
    private String email;
    @NotBlank
    private String password;
}
